package com.xuebank.nfe.nfecar.beas

import android.app.Service
import android.support.annotation.CallSuper
import android.support.annotation.CheckResult
import com.trello.rxlifecycle.LifecycleProvider
import com.trello.rxlifecycle.LifecycleTransformer
import com.trello.rxlifecycle.OutsideLifecycleException
import com.trello.rxlifecycle.RxLifecycle
import rx.Observable
import rx.functions.Func1
import rx.subjects.BehaviorSubject

/**
 * Created by Wind_Fantasy on 2017/5/2.
 */
abstract class BaseService : Service(), LifecycleProvider<ServiceEvent> {
    val TAG = javaClass.simpleName

    private val lifecycleSubject = BehaviorSubject.create<ServiceEvent>()

    @CheckResult
    override fun lifecycle(): Observable<ServiceEvent> {
        return lifecycleSubject.asObservable()
    }

    @CheckResult
    override fun <T> bindUntilEvent(event: ServiceEvent): LifecycleTransformer<T> {
        return RxLifecycle.bindUntilEvent<T, ServiceEvent>(lifecycleSubject, event)
    }

    @CheckResult
    override fun <T> bindToLifecycle(): LifecycleTransformer<T> {
        return RxLifecycle.bind(lifecycleSubject, FRAGMENT_LIFECYCLE)
    }

    @CallSuper
    override fun onCreate() {
        super.onCreate()
        lifecycleSubject.onNext(ServiceEvent.CREATE)
    }


    @CallSuper
    override fun onDestroy() {
        lifecycleSubject.onNext(ServiceEvent.DESTROY)
        super.onDestroy()
    }

    private val FRAGMENT_LIFECYCLE = Func1<ServiceEvent, ServiceEvent> { lastEvent ->
        when (lastEvent) {
            ServiceEvent.CREATE -> ServiceEvent.CREATE
            ServiceEvent.DESTROY ->
                throw OutsideLifecycleException("Cannot bind to Service lifecycle when outside of it.")
            else ->
                throw UnsupportedOperationException("Binding to $lastEvent not yet implemented")
        }
    }
}